import base64
import hashlib
import json
import requests
import time, datetime
from functools import wraps


class pre_api_get:
    def __init__(self):
        self.appkey = "1bN0kRdX8DVPGGvD5UdP"
        self.appSecret = "LzHQEv5nH8umSviagRdhK3lAJrYSMJpqe8QDuO8o"
        self.openid = "kjvb46f04fZ4uHQAbBBM"

        self.api = "https://gateway.rjmart.cn/open/shop"
        self.pre_api = "https://gateway.test.rj-info.com/open/shop"

    # 获取Authorization_Code
    def get_Authorization_Code(self):
        url = "https://www.rjmart.cn/auth/oauth/authorize"
        response = requests.get(url=url)
        return response

    # 通过Authorization_Code获取Access_Token
    def ac_get_Access_Token(self):
        url = "https://www.rjmart.cn/auth/oauth/token"
        response = requests.post(url=url)
        return response

    # 通过openid获取Access_Token
    def openid_Access_Token(self):
        url = "https://www.rjmart.cn/auth/openid/login"
        md5 = hashlib.md5()
        md5.update(self.appSecret.encode("utf-8"))  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        data = {"openid": self.openid, "sign": sign}
        response = requests.post(url=url, data=data)
        results = json.loads(response.content.decode("utf-8"))
        t = time.time()
        results.update({"time": t})
        with open("Access_Token.json", mode="w") as f:
            f.write(json.dumps(results))
        # with open('main_dir/Access_Token.json', mode='w') as f2:
        #     f2.write(json.dumps(results))
        return results

    # api基础模板
    def no_data(self, url, name, data=""):
        time_now = time.time()
        with open("Access_Token.json") as j:
            ac_json = json.load(j)
        Access_Token = ac_json["access_token"]
        time_acc = ac_json["time"]
        if time_now - time_acc > 600:
            Access_Token = self.openid_Access_Token()["access_token"]
        header = {
            "Authorization": f"Bearer {Access_Token}",
            "Content-Type": "application/json;charset=utf-8",
        }
        json_post_data = self.appSecret + data
        # data = json.loads(data)
        md5 = hashlib.md5()
        md5.update(json_post_data.encode("utf-8"))  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        s_url = f"{self.api}{url}?appkey={self.appkey}&sign={sign}"
        # print(s_url)
        response = requests.post(url=s_url, data=data.encode("utf-8"), headers=header)
        results = response.content.decode("utf-8")
        with open(f"{name}.json", mode="w", encoding="utf-8") as f:
            f.write(results)
        return response

    # 查询所有运费模板
    def findTemplate(self):
        url = "/openapi/product/findTemplate"
        name = "findTemplate"
        return self.no_data(url, name)

    # 查询商品标准单位与规格
    def UnitAndSpec(self):
        url = "/openapi/product/queryUnitAndSpecification"
        name = "UnitAndSpec"
        return self.no_data(url, name)

    # 查询入驻单位
    def settledOgrList(self):
        url = "/openapi/product/settledOgrList"
        name = "settledOgrList"
        return self.no_data(url, name)

    # 商品树形分类查询
    def AllCategoryTree(self):
        url = "/openapi/product/queryAllCategoryTree"
        name = "AllCategoryTree"
        return self.no_data(url, name)

    # 商品品牌查询
    def getSuppBrands(self):
        url = "/openapi/product/getSuppBrands"
        name = "getSuppBrands"
        return self.no_data(url, name)

    # 查询商品一级分类的属性（一级分类Id）
    def CategoryAttribute(self, categoryId):
        url = "/openapi/product/queryCategoryAttribute"
        name = "CategoryAttribute" + str(categoryId)
        data = json.dumps({"categoryId": categoryId})
        return self.no_data(url, name, data=data)

    # 批量查询商品（"status" : 3,      2:草稿，3:上架，4下架，5强制下架，12待审核，15已驳回
    #     "brandIds" : [2],         品牌列表
    #     "categoryId" : 1671,      分类id
    #     "productNum" : "202200",  商品货号
    #     "productName" : "测试商品"） 商品名
    def ProductList(self, page, add_data="{}"):
        url = "/openapi/product/queryProductList"
        data = {"page": page, "size": 100}
        data.update(json.loads(add_data))
        name = "ProductList" + "&".join(list(map(str, data["brandIds"])))
        return self.no_data(url, name, data=json.dumps(data))

    # 查询单个商品内容（id）
    def ProductDetail(self, ProductId):
        url = "/openapi/product/queryProductDetail"
        name = "ProductDetail" + str(ProductId)
        data = json.dumps({"id": ProductId})
        return self.no_data(url, name, data=data)

    # 上架商品（id_list/code_list）
    def onSale(self, ProductId_list):
        url = "/openapi/product/onSale"
        name = "onSale"
        data = json.dumps({"productIdList": ProductId_list})
        return self.no_data(url, name, data=data)

    # 删除商品（id_list/code_list）
    def deleteProduct(self, ProductCode_list):
        url = "/openapi/product/deleteProductList"
        name = "deleteProductList"
        data = json.dumps({"productCodeList": ProductCode_list})
        return self.no_data(url, name, data=data)

    # 下架商品（id_list/code_list）
    def offSale(self, ProductId_list):
        url = "/openapi/product/offShelves"
        name = "offSale"
        data = json.dumps({"productCodeList": ProductId_list})
        return self.no_data(url, name, data=data)

    # 撤销商品审核（id_list/code_list）
    def cancelReview(self, ProductId_list):
        url = "/openapi/product/cancelReview"
        name = "cancelReview"
        data = json.dumps({"productIdList": ProductId_list})
        return self.no_data(url, name, data=data)

    # 单个新增、更新
    def saveOrUpdateProduct(self, json_data):
        url = "/openapi/product/saveOrUpdateProduct"
        name = "saveOrUpdateProduct"
        return self.no_data(url, name, data=json_data)

    # 批量更新（可部分更新）
    def updateProductInfoByCode(self, json_data):
        url = "/openapi/product/updateProductInfoByCode"
        name = "updateProductInfoByCode"
        return self.no_data(url, name, data=json_data)


# if __name__ == "__main__":
# rj_api = pre_api_get()
# # 先获取Token(已内置）
# rj_api.openid_Access_Token()
# # 对接
# responses = rj_api.saveOrUpdateProduct(
#     json_data=json.dumps(
#         {
#             # "id": "200001000020",#* 商品id{未传情况：【若传入的productNum已存在系统中，系统判定为编辑商品,若传入的productNum不存在系统中，系统判定为新增商品】，已传情况：【编辑商品】}
#             "productNum": "S2150",  #! 商品货号（必须要具有商品唯一性）
#             "price": 160.00,  #! 统一售价, 保留两位小数(若商品品牌已签署平台协议价, 则售价不能高于“协议上限折扣价”(协议上限折扣价 = 目录价 * 协议价上限折扣))
#             # "directoryPrice": 800.00,#*目录价, 保留两位小数(若商品品牌签署了协议价必传, 未签署选传)
#             "name": "抗A抗B血型定型试剂",  #!商品名称（若传入的是危化品且不符合危化品标准库的名称，系统会自动补全危化品名称）
#             "specification": "2*10ml/盒",  # *商品规格, 除一级分类为化学试剂或危险化学品或工业品无需传外, 其他分类必传
#             "status": 3,  # 2:保存草稿状态  3:上架操作
#             "categoryId": 531,  #!商品所属分类id, 必须是二级或者三级, 医疗试剂耗材类的必须是三级. (数据来源: 查询分类列表的接口/openapi/product/queryAllCategoryTree)
#             # "brandId": 3,#*商品所属品牌id. (数据来源: 查询品牌列表的接口: /openapi/product/getSuppBrands)
#             "sku": 1000,  #!库存数量
#             "unit": "箱",  #!销售单位, 不可自定义, 必须使用平台的标准销售单位 (数据来源: 查询标准单位、包装规格和最小包装规格列表的接口/openapi/product/queryUnitAndSpecification)
#             "desc": '<b>培养瓶，测试</b>。<div>@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@<br><div><span classname="ZenEditor-parse-img-wrap"><img classname="ZenEditor-parse-img " src="https://images-test.rjmart.cn/file/19a274c2/ceba044a-0647-4a24-93d5-90c447bb3c45.jpg" style="cursor: nesw-resize;"></span></div></div>',  #!	商品介绍 (支持富文本格式)
#             "photos": [  #!商品图库 (程序会截取第一张图为主图 , 一共不能超过5张图) , 见下方ProductPhotoDTO
#                 {
#                     "photo": "https://images-test.rjmart.cn/image/5b7e3821/ee56c407-deb7-4055-badd-12b75adf494a.jpg"
#                 },
#                 {
#                     "photo": "https://images-test.rjmart.cn/image/5b7e3821/6ba2b8f9-6024-47a5-8858-5515074b9b2c.jpg"
#                 },
#                 {
#                     "photo": "https://images-test.rjmart.cn/image/5b7e3821/2a9b1b72-02dd-4d97-9b24-0a80e6aeaa9d.jpg"
#                 },
#                 {
#                     "photo": "https://images-test.rjmart.cn/image/5b7e3821/171eb160-f1be-493c-a5a1-79b651e7d64c.jpg"
#                 },
#                 {
#                     "photo": "https://images-test.rjmart.cn/image/5b7e3821/9ea617ae-3d02-492f-8e2b-409fba70c1b6.jpg"
#                 },
#             ],
#             # "priceDifferents": [#*单位差异价模型 , 见下方ProductDiffPriceModel
#             #     {"orgId": 2, "price": 400.00},
#             #     {"orgId": 5, "price": 450.00},
#             # ],
#             "deliveryTime": 7,  #!货期[[[1	现货],[7	1周内],[14	2周],[21	3周],[30	1个月],[60	2个月],[61	2个月以上],[-1	咨询供应商客服]]]
#             # "carryFeeTemplateId": 130,#*运费模版Id, 全国包邮不用传(数据来源 : 查询商家所有运费模板/openapi/product/findTemplate)
#             # "attributes": [#*商品属性模型 , 见下方AttributesVO
#             #     {"attributeName": "英文名称", "attributeNameValue": "EnglishName"},
#             #     {"attributeName": "保存条件", "attributeNameValue": "冷藏"},
#             # ],
#         }
#     ).replace(" ", "")
# )
# result = responses.content.decode("utf-8")
# print(responses)
# print(result)
